local M = {}
-- Function to split a string by a given delimiter
function M.split(str, delimiter)
	local result = {}
	for match in (str .. delimiter):gmatch("(.-)" .. delimiter) do
		table.insert(result, match)
	end
	return result
end

-- Function to trim whitespace from a string
function M.trim(s)
	return s:match("^%s*(.-)%s*$")
end

-- Function to join multiline curl command into a single line
function M.join_multiline(curl_command)
	local single_line = ""
	local lines = {}
	for line in curl_command:gmatch("[^\r\n]+") do
		if line:sub(-1) == "\\" then
			single_line = line:sub(1, -2)
		else
			single_line = line
		end
		table.insert(lines, M.trim(single_line))
	end
	return lines
end

-- Function to convert curl command to HTTP format
function M.curl_to_http(curl_command)
	-- Join multiline command
	print("curl_command: " .. curl_command)
	local lines = M.join_multiline(curl_command)

	-- Initialize variables
	local method = "GET"
	local url = ""
	local headers = {}
	local data = ""
	-- Split the curl command into parts
	local parts = lines

	-- Parse the parts of the curl command

	for i = 1, #parts do
		local curl_line = parts[i]
		if curl_line:match("-H") then
			local header = curl_line:match("'.*'")
			local s = string.gsub(header, "'", "")
			table.insert(headers, s)
		elseif curl_line:match("-d") or curl_line:match("--data") then
			method = "POST"
		elseif curl_line:match("(https?)://.*'") then
			local u = curl_line:match("'.*'")
			url = string.gsub(u, "'", "")
		end
	end

	-- Build the HTTP request
	local http_request = method .. " " .. url .. " HTTP/1.1\n"
	for _, header in ipairs(headers) do
		http_request = http_request .. header .. "\n"
	end

	if data ~= "" then
		http_request = http_request .. "\n" .. data
	end

	return http_request
end

return M
